package com.omg.api.handle;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.MessageArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.MessageBody;
import com.omg.api.result.header.MessageHeader;
import com.omg.constant.Constants;
import com.omg.constant.LPUtility;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPMessage;
import com.omg.persistence.dao.lifepoint.entity.LPMessageRelation;
import com.omg.persistence.delegate.lifepoint.LPMessageDelegate;
import com.omg.persistence.delegate.lifepoint.LPMessageRelationDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class MessageHandler extends Handler {

	private static final Logger LOG = Logger.getLogger(MessageHandler.class
			.getName());

	private static MessageHandler instance = null;

	static {
		instance = new MessageHandler();
	}

	public static MessageHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String messageid = ((MessageArgument) argument).getMessageid();
		String sender = ((MessageArgument) argument).getSender();
		String owner = ((MessageArgument) argument).getOwner();
		String content = ((MessageArgument) argument).getContent();
		String action = ((MessageArgument) argument).getAction();

		List<LPMessage> messages = null;

		if (action.equals(Constants.ACTION_POST)) {
			LPMessage message = new LPMessage();
			if (messageid != null && !messageid.isEmpty()) {
				message.setMessageid(messageid);
			} else {
				message.setMessageid(LPUtility.getMessageId());
			}
			message.setContent(content);
			message.setOwner(owner);
			message.setSender(sender);
			message.setSendtime(System.currentTimeMillis());
			int ret = LPMessageDelegate.getInstance().addOrReplaceLPMessage(
					message);
			if (ret != 0) {
				throw new Exception(""
						+ ResponseCode.AP_E_Info_PostMessageFailed);
			}

			LPMessageRelation lpMessageRelation = new LPMessageRelation();
			lpMessageRelation.setId(LPUtility.getMessageId());
			lpMessageRelation.setMessageid(message.getMessageid());
			lpMessageRelation.setContent(content);
			lpMessageRelation.setOwner(owner);
			lpMessageRelation.setSender(sender);
			lpMessageRelation.setSendtime(message.getSendtime());
			ret = LPMessageRelationDelegate.getInstance().addLPMessageRelation(
					lpMessageRelation);
			if (ret != 0) {
				throw new Exception(""
						+ ResponseCode.AP_E_Info_PostMessageFailed);
			}

			List<LPMessageRelation> lpMessageRelations = LPMessageRelationDelegate
					.getInstance().getLPMessageRelationsByMessageId(
							message.getMessageid());
			messages = new ArrayList<LPMessage>();
			for (LPMessageRelation m : lpMessageRelations) {
				message = new LPMessage();
				message.setContent(m.getContent());
				message.setMessageid(m.getMessageid());
				message.setOpentime(m.getOpentime());
				message.setOwner(m.getOwner());
				message.setSender(m.getSender());
				message.setSendtime(m.getSendtime());
				messages.add(message);
			}
		}

		// else if (action.equals(Constants.ACTION_DELETE)) {
		// message = LPMessageDelegate.getInstance().getLPMessage(messageid);
		//
		// if (message == null) {
		// throw new Exception(""
		// + ResponseCode.AP_E_Info_InvalidMessageId);
		// }
		//
		// int ret = LPMessageDelegate.getInstance().delLPMessage(messageid);
		//
		// if (ret != 0) {
		// throw new Exception(""
		// + ResponseCode.AP_E_Info_DeleteMessageFailed);
		// }
		//
		// }

		else if (action.equals(Constants.ACTION_GET)) {
			messages = new ArrayList<LPMessage>();
			if (messageid != null && !messageid.isEmpty()) {
				List<LPMessageRelation> lpMessageRelations = LPMessageRelationDelegate
						.getInstance().getLPMessageRelationsByMessageId(
								messageid);
				if (lpMessageRelations == null) {
					throw new Exception(""
							+ ResponseCode.AP_E_Info_InvalidMessageId);
				}
				for (LPMessageRelation lpMessageRelation : lpMessageRelations) {
					LPMessage message = new LPMessage();
					message.setContent(lpMessageRelation.getContent());
					message.setMessageid(lpMessageRelation.getMessageid());
					message.setOpentime(lpMessageRelation.getOpentime());
					message.setOwner(lpMessageRelation.getOwner());
					message.setSender(lpMessageRelation.getSender());
					message.setSendtime(lpMessageRelation.getSendtime());
					messages.add(message);
				}
			} else {
				List<LPMessage> ms = LPMessageDelegate.getInstance()
						.getLPMessageByUserid(sender);
				if (ms != null) {
					messages.addAll(ms);
				}
			}
		}
		return getJson(messages);
	}

	private final String getJson(List<LPMessage> messages) throws Exception {
		try {

			// construct result
			Result result = new Result();

			// header
			MessageHeader header = new MessageHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			result.setHeader(header);

			// body
			MessageBody body = new MessageBody();
			body.setMessages(messages);
			result.setBody(body);

			return new Gson().toJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			LOG.error(errorMsg, e);
			throw new Exception(""
					+ (errorMsg != null && !errorMsg.isEmpty() ? errorMsg
							: ResponseCode.AP_E_Info_UnkownError));
		}
	}

}
